# -*- coding: utf-8 -*-

'''
豆瓣查书功能
=====================================================
搜索图书
{
  "start": 0,
  "count": 10,
  "total": 30,
  "books" : [Book, ]
}

图书信息 Book
{
    "id":"1003078",
    "isbn10":"7505715666",
    "isbn13":"9787505715660",
    "title":"小王子",
    "origin_title":"",
    "alt_title":"",
    "subtitle":"",
    "url":"http:\/\/api.douban.com\/v2\/book\/1003078",
    "alt":"http:\/\/book.douban.com\/subject\/1003078\/",
    "image":"http:\/\/img1.douban.com\/mpic\/s1001902.jpg",
    "images":{
        "small":"http:\/\/img1.douban.com\/spic\/s1001902.jpg",
        "large":"http:\/\/img1.douban.com\/lpic\/s1001902.jpg",
        "medium":"http:\/\/img1.douban.com\/mpic\/s1001902.jpg"
        },
    "author":[
        "（法）圣埃克苏佩里"
        ],
    "translator":[
        "胡雨苏"
        ],
    "publisher":"中国友谊出版公司",
    "pubdate":"2000-9-1",
    "rating":{"max":10,"numRaters":9438,"average":"9.1","min":0},
    "tags":[
        {"count":2416,"name":"小王子"},
        {"count":1914,"name":"童话"},
        {"count":1185,"name":"圣埃克苏佩里"},
        {"count":863,"name":"法国"},
        {"count":647,"name":"经典"},
        {"count":597,"name":"外国文学"},
        {"count":495,"name":"感动"},
        {"count":368,"name":"寓言"}
        ],
    "binding":"平装",
    "price":"19.8",
    "series": {
        "id": "2065",
        "title": "新史学&多元对话系列"
    },
    "pages":"111",
    "author_intro":"圣埃克苏佩里（1900－1944）1900年，尼采逝世。..."
    "summary":"小王子驾到！大家好，我是小王子，生活在B612星球，..."
    "catalog":"序言：法兰西玫瑰\n小王子\n圣埃克苏佩里年表\n",
    "ebook_url":"http://read.douban.com/ebook/1234567/(该字段只在存在对应电子书时提供)",
    "ebook_price": "12.00"
}
'''

from private_key import DOUBAN_API_KEY
import urllib2
import urllib
import json

#访问豆瓣API获取书籍数据
BOOK_URL_BASE = 'http://api.douban.com/v2/book/search'
def douban_make_articlelist(books):
    books_article = []
    art_item = ('title', 'description', 'picurl', 'url')
    if len(books) == 1:
        book = books[0]
        art_title = u'%s\t%s分' % (book['title'], book['rating']['average'])
        art_desc = '%s\n%s\t%s' % (','.join(book['author']), book['publisher'], book['price'])
        art_picurl = book['images']['large']
        art_url = book['alt']
        books_article.append(dict(zip(art_item, (art_title, art_desc, art_picurl, art_url))))
    else:
        for i, book in enumerate(books):
            art_title = u'%s\t%s分\n%s\n%s\t%s' % (book['title'], book['rating']['average'], ','.join(book['author']), book['publisher'], book['price'])
            art_desc = ''
            art_picurl = book['images']['large'] if i == 1 else book['images']['small']
            art_url = book['alt']
            books_article.append(dict(zip(art_item, (art_title, art_desc, art_picurl, art_url))))
    return books_article
    
def douban_search_book(q):
    params = {'q': q.encode('utf-8'), 'apikey': DOUBAN_API_KEY, 'count': 3}
    url = BOOK_URL_BASE + '?' + urllib.urlencode(params)
    resp = urllib2.urlopen(url)
    r = json.loads(resp.read())
    books = r['books']
    return douban_make_articlelist(books)

